#! /bin/bash

sudo echo "Locating scripts..."
export TOPDIR=$(readlink -f $0 | grep -Eo "/\S+/") && echo "Done."

# 如果没有snap，退出
if [ -z "$(sudo which snap)" ];then
	echo "Snap isn't found. Exit."
	exit
else
	echo "Find snapd." 
fi

# 先判断有没有snap的包
NAME_ARR=($(snap list 2>/dev/null | grep -Eo "^(\S+)" | tail -n +2)) 
if [ -n "${NAME_ARR}" ];then
	echo -e "Snap packages found will be written to 'snap_cleaner_log.txt'\n"
	# 写log
	echo "${NAME_ARR[*]}" > ${TOPDIR}/snap_cleaner_log.txt

	echo -e "Find snap packages:\n\t${NAME_ARR[*]}\nCleaning snap packages..."
	LAST_SIZE=0
	while [ ${#NAME_ARR[@]} -ne 0 ]; do
		# 防止死循环
		if [ ${#NAME_ARR[@]} -eq ${LAST_SIZE} ];then
			echo "Unable to remove the rest snap packages. Exit"
			exit
		else
			LAST_SIZE=${#NAME_ARR[@]}
		fi

		# 尝试删除
		for NAME in ${NAME_ARR[*]}; do
			sudo snap remove --purge ${NAME} &>> /dev/null
		done
		# 刷新
		NAME_ARR=($(snap list 2>/dev/null | grep -Eo "^(\S+)" | tail -n +2)) 
	done
	echo "Done."
else
	echo "No snap package found."
fi

echo "Cleaning snapd..."
sudo apt-get remove -y snapd >/dev/null && echo "Done."

echo -e "\nConfiging the apt preference so that snap won't come back while updating..."
echo -e "Package: snapd\nPin: release a=*\nPin-Priority: -10" | sudo tee /etc/apt/preferences.d/nosnap.pref > /dev/null && echo "Done."

exit
